//
//  BCMLoginViewController.m
//  BCManagerVersion
//
//  Created by 吴 崧 on 14-2-22.
//  Copyright (c) 2014年 Jungle. All rights reserved.
//

#import "BCLoginViewController.h"
#import "BCRegistrationViewController.h"


@interface BCLoginViewController ()<UITextFieldDelegate>

@property(nonatomic,strong)UITextField *firstResponsTF;

@end

@implementation BCLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _firstResponsTF = nil;
    }
    return self;
}

+(void)show
{
    BCLoginViewController *logInVC = [[BCLoginViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:logInVC];
    [nav.navigationBar setHidden:YES];
    [APP_Delegate.window.rootViewController presentViewController:nav animated:YES completion:^{
        
    }];
}

+ (void)checkLoggedInWithBlock:(LoginCheckBlock)complete
{
    if (USER_MANAGER.didLogin && complete){
        complete(YES);
        complete = nil;
    }
    else
    {
        BCLoginViewController *logInVC = [[BCLoginViewController alloc]init];
        logInVC.complete = complete;
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:logInVC];
        [nav.navigationBar setHidden:YES];
        [APP_Delegate.window.rootViewController presentViewController:nav animated:YES completion:^{
            
        }];
    }
}


- (IBAction)forgetPassword:(UIButton *)sender {
    [BCProgressHUD showWithTile:@"加载中" animated:YES];
    [BCNetworkClient forgetPasswordSuccess:^(NSString *message) {
        
        [BCProgressHUD hideAnimated:YES];
        ExhibitionView *ex = [[ExhibitionView alloc]initWithString:message];
        [ex Show];
        
    } failure:^(NSError *error) {
        [BCProgressHUD hideWithError:error animated:YES];
    }];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.logPasswordTextField.delegate = self;
    self.logAccountTextField.delegate = self;
    [self addFunctionToEndEdit];
    NSLog(@"%@",USER_MANAGER);
    // Do any additional setup after loading the view from its nib.
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    if([textField isEqual:self.logPasswordTextField])
    {
        [self loginBtnPressed:nil];
    }
    return YES;
}


- (IBAction)back:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.complete) {
            self.complete(USER_MANAGER.didLogin);
            self.complete = nil;
        }
    }];
}

- (IBAction)regesiter:(UIButton *)sender {
    BCRegistrationViewController *reg = [[BCRegistrationViewController alloc]init];
    [self.navigationController pushViewController:reg animated:YES];
}

- (IBAction)loginBtnPressed:(UIButton *)sender {
    [self.view endEditing:YES];
     __weak typeof(self)weakSelf = self;
    if(self.logAccountTextField.text.length == 0||self.logPasswordTextField.text.length == 0)
    {
        NSString *alertString = @"请输入用户名/密码";
        [UIAlertView showWithTitle:nil
                           message:alertString
                 cancelButtonTitle:@"确定"
                 otherButtonTitles:nil
                          tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                          }];
        
    }else{

        [BCProgressHUD showWithTile:@"登陆中" animated:YES];
        [BCNetworkClient loginWithPassport:self.logAccountTextField.text
                                  password:self.logPasswordTextField.text
                                      type:ClientType
                                   success:^(int uid, NSString *auth) {
                                       USER_MANAGER.uid = @(uid);
                                       USER_MANAGER.auth = auth;
                                       
                                       NSString *devStr = [[NSUserDefaults standardUserDefaults] valueForKey:BCDeviceTokenKey];
                                       if (devStr.length > 0) {
                                           [BCNetworkClient bindPhoneId:devStr
                                                                   auth:USER_MANAGER.auth
                                                                success:^{
                                                                    
                                                                } failure:^(NSError *error) {
                                                                    
                                                                }];
                                       }
                                       
                                       if (weakSelf.complete) {
                                           weakSelf.complete(YES);
                                           weakSelf.complete = nil;
                                       }
                                       [BCProgressHUD hideAnimated:YES];
                                       [weakSelf dismissViewControllerAnimated:YES completion:^{
                                       }];
                                       
                                   } failure:^(NSError *error) {
                                       
                                       [BCProgressHUD hideWithError:error animated:YES];
                                       
                                       
                                   }];
    }

}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}


-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}





- (void)keyboardWillShow:(NSNotification *)aNotification
{
    NSDictionary *userInfo = [aNotification userInfo];
    
    
	CGRect keyboardFrameBefore = CGRectApplyAffineTransform([userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue], CGAffineTransformInvert(APP_Delegate.window.rootViewController.view.transform));
    
	CGRect keyboardFrameAfter = CGRectApplyAffineTransform([userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue], CGAffineTransformInvert(APP_Delegate.window.rootViewController.view.transform));
    
    CGFloat dHeight = 0;
    dHeight = keyboardFrameBefore.origin.y - keyboardFrameAfter.origin.y;
    
	if (dHeight != 0) {
        //CGFloat posY = self.view.frame.origin.y - dHeight;
        CGRect frame = CGRectSetY(self.view.frame, -170);
		
		[UIView animateWithDuration:[userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]
		                      delay:0
		                    options:[userInfo[UIKeyboardAnimationCurveUserInfoKey] intValue]
		                 animations: ^(void) {
                             self.view.frame = frame;
                         }
		                 completion: ^(BOOL finished) {
                             
                         }
         ];
	}
    
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
	NSDictionary *userInfo = [aNotification userInfo];
    
    
	CGRect keyboardFrameBefore = CGRectApplyAffineTransform([userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue], CGAffineTransformInvert(APP_Delegate.window.rootViewController.view.transform));
    
	CGRect keyboardFrameAfter = CGRectApplyAffineTransform([userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue], CGAffineTransformInvert(APP_Delegate.window.rootViewController.view.transform));
    
	CGFloat dHeight = 0;
    dHeight = keyboardFrameBefore.origin.y - keyboardFrameAfter.origin.y;
    if (dHeight != 0) {
        // CGFloat posY = self.view.frame.origin.y - dHeight;
        CGRect frame = CGRectSetY(self.view.frame, 0);
        
		
		[UIView animateWithDuration:[userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]
		                      delay:0
		                    options:[userInfo[UIKeyboardAnimationCurveUserInfoKey] intValue]
		                 animations: ^(void) {
                             self.view.frame = frame;
                         }
		                 completion: ^(BOOL finished) {
                             
                         }
         ];
	}
}




-(BOOL)prefersStatusBarHidden
{
    return YES;
}

@end
